// Activity to add pill information into the database. The PillListFragment links
// to this activity. Save button will save the information into the database and finish
// This activity. The cancel button will automatically finish this activity.

package com.pillpoppers.pillbox;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.pillpoppers.pillbox.contentprovider.PillContentProvider;
import com.pillpoppers.pillbox.database.PillTable;

// Activity to create or edit changes to pill database.
public class AddPillActivity extends Activity {
  	EditText nameEditText;
	EditText currentCountEditText;
	EditText descriptionEditText;
	EditText warningsEditText;
	EditText sideEffectsEditText;
	EditText contactEditText;
	EditText maximumCountEditText;
	CheckBox checkedCritical;
	Button addPillSaveButton;
	Button addPillCancelButton;
	Button addPillDeleteButton;
	String typeCritical;
	String schedule;

  private Uri pillUri;

  @Override
  protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.activity_add_pill);

    nameEditText = (EditText) findViewById(R.id.nameEditText);
    descriptionEditText = (EditText) findViewById(R.id.descriptionEditText);
    currentCountEditText = (EditText) findViewById(R.id.currentCountEditText);
    maximumCountEditText = (EditText) findViewById(R.id.maximumCountEditText);
    warningsEditText = (EditText) findViewById(R.id.warningsEditText);
    sideEffectsEditText = (EditText) findViewById(R.id.sideEffectsEditText);
    contactEditText = (EditText) findViewById(R.id.contactEditText);
    addPillSaveButton = (Button) findViewById(R.id.addPillSaveButton);
    addPillCancelButton = (Button) findViewById(R.id.addPillCancelButton);
    addPillDeleteButton = (Button) findViewById(R.id.addPillDeleteButton);
    checkedCritical = (CheckBox) findViewById(R.id.checkedCritical);
    	checkedCritical.setChecked(false);
    
    // Data base use?
    Bundle extras = getIntent().getExtras();

    // Check from the saved Instance
    pillUri = (bundle == null) ? null : (Uri) bundle.getParcelable(PillContentProvider.CONTENT_ITEM_TYPE);
    //typeCritical = "";
    schedule = "";
    // Or passed from the other activity
    if (extras != null)
    {
      pillUri = extras.getParcelable(PillContentProvider.CONTENT_ITEM_TYPE);
      fillData(pillUri);
    }

    // Actions for the Save Button
    addPillSaveButton.setOnClickListener(new View.OnClickListener()
    {
    	public void onClick(View view)
    	{
    		if(TextUtils.isEmpty(nameEditText.getText().toString()))
    		{
    			makeToast();
    		}
    		else
    		{
    			setResult(RESULT_OK);
    			saveState();
    			finish();
    		}
    	}
    });
    
    // Actions for clicking the Cancel Button
    addPillCancelButton.setOnClickListener(new View.OnClickListener()
    {
    	public void onClick(View view)
    	{
    		setResult(RESULT_CANCELED);
    		finish();
       	}
    });
    
  //Actions for the Save Button
    addPillDeleteButton.setOnClickListener(new View.OnClickListener()
    {
    	public void onClick(View view)
    	{
    		if(pillUri != null)
    		{
    			String message = "Are you sure?";
    			String button1 = "No";
    			String button2 = "Yes";
    			
    			AlertDialog.Builder ad = new AlertDialog.Builder(AddPillActivity.this);
    			ad.setMessage(message);
    			
    			ad.setPositiveButton(button2, new DialogInterface.OnClickListener() {
    				
    				@Override
    				public void onClick(DialogInterface dialog, int which) {
    					getContentResolver().delete(pillUri, null, null);
    	    			setResult(RESULT_OK);
    	    			finish();
    				}
    			});
    			
    			ad.setNegativeButton(button1, new DialogInterface.OnClickListener() {
    				
    				@Override
    				public void onClick(DialogInterface dialog, int which) {
    	    		// Do Nothing
    				}
    			})
    			.create()
    			.show();
    		}
    	}
     });
   }

  // Actions when the Check Box is clicked for critical medications.
  public void onCheckboxClicked(View view)
  {
	    boolean checked = ((CheckBox) view).isChecked();

	    switch(view.getId()) {
	        case R.id.checkedCritical:
	            if (checked)
	                typeCritical = "true";
	            else
	                typeCritical = "false";
	            break;
	      }
	}
  
  // Method that fills in the pill list view with information from the database.
  private void fillData(Uri uri)
  {
	  // Include for accessing database
	 String[] projection = { PillTable.COLUMN_TYPE, PillTable.COLUMN_NAME, PillTable.COLUMN_DESCRIPTION, 
			                 PillTable.COLUMN_CURRENT_COUNT, PillTable.COLUMN_MAX_COUNT, PillTable.COLUMN_WARNINGS, 
			                 PillTable.COLUMN_SIDE_EFFECTS, PillTable.COLUMN_CONTACT };
	 // Set cursor
	  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    
	  	// Position cursor
		 if (cursor != null) {
		     cursor.moveToFirst();
		     
		     // For setting critical check box
		  String type = cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_TYPE));
		  
		  if(type.equals("true"))
		    	  checkedCritical.setChecked(true);
		     else
		    	 checkedCritical.setChecked(false);

		  // move back
		 // cursor.moveToFirst();

		  // other fields to be filled out. 
		  nameEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_NAME)));
		  descriptionEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_DESCRIPTION)));
		  currentCountEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_CURRENT_COUNT)));
		  maximumCountEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_MAX_COUNT)));
		  warningsEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_WARNINGS)));
		  sideEffectsEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_SIDE_EFFECTS)));
		  contactEditText.setText(cursor.getString(cursor.getColumnIndexOrThrow(PillTable.COLUMN_CONTACT)));
		  
		  // shut down
		  cursor.close();
		 	}
  }

  protected void onSaveInstanceState(Bundle outState)
  {
	  super.onSaveInstanceState(outState);
	//  saveState();
	  outState.putParcelable(PillContentProvider.CONTENT_ITEM_TYPE, pillUri);
  }

  @Override
  protected void onPause()
  {
	  super.onPause();
	 // saveState();
  }

  private void saveState() {
    //String type = typeCritical; /broke
	String type = "";  //patch
    String name = nameEditText.getText().toString();
    String description = descriptionEditText.getText().toString();
    String current_count = currentCountEditText.getText().toString();
    String maxCount = maximumCountEditText.getText().toString();
    String contact = contactEditText.getText().toString();
    String warnings = warningsEditText.getText().toString();
    String sideEffects = sideEffectsEditText.getText().toString();
    
    // Fixed to add 0s instead of nothing.
    if(current_count.equals(""))
    	current_count ="0";
    if(maxCount.equals(""))
    	maxCount ="0";
    
    ContentValues values = new ContentValues();
    values.put(PillTable.COLUMN_TYPE, type);
    values.put(PillTable.COLUMN_NAME, name);
    values.put(PillTable.COLUMN_CURRENT_COUNT, current_count);
    values.put(PillTable.COLUMN_MAX_COUNT, maxCount);
    values.put(PillTable.COLUMN_DESCRIPTION, description);
    values.put(PillTable.COLUMN_WARNINGS, warnings);
    values.put(PillTable.COLUMN_SIDE_EFFECTS, sideEffects);
    values.put(PillTable.COLUMN_CONTACT, contact);
    values.put(PillTable.COLUMN_SCHEDULE, schedule);
    
    if (pillUri == null)
    {
    	// New pill
    	pillUri = getContentResolver().insert(PillContentProvider.CONTENT_URI, values);
    }
    else
    {
      // Update pill
      getContentResolver().update(pillUri, values, null, null);
    }
  }

 private void makeToast()
  {
    Toast.makeText(AddPillActivity.this, "Please enter a name.", Toast.LENGTH_LONG).show();
  }
} 